import { createRouter, createWebHistory } from "vue-router";
import Index from "../views/index.vue";
import { useSysStore } from "../store/index.js";

const routes = [
    { path: "/", redirect: "/workbench/index" },
    {
        path: "/workbench/design/:id",
        name: "workbenchDesign",
        component: () => import("../views/workbench/design/index.vue"),
    },
    {
        path: "/login",
        name: "login",
        component: () => import("../views/sys/login/index.vue"),
        meta: {
            public: true,
        },
    },
    {
        path: "/404",
        name: "404",
        component: () => import("../views/sys/404.vue"),
        meta: {
            public: true,
        },
    },
];

const router = createRouter({
    routes,
    history: createWebHistory(),
});

const componentMap = import.meta.glob("../views/**/*.vue");

router.beforeEach((to, from) => {
    if (to.fullPath == "/") {
        return;
    }

    let appCode = to.fullPath.match(/\/([^\/]*)\//);
    if (!appCode) {
        appCode = to.fullPath.match(/\/(.*)/)[1];
    } else {
        appCode = appCode[1];
    }
    const sysStore = useSysStore();

    if (appCode == sysStore.currentAppCode) {
        return;
    } else if (router.hasRoute(to.name) && to.name != "app") {
        return;
    }
    sysStore.currentAppCode = appCode;
    let appRoutes = [];
    if (appCode == "workbench") {
        appRoutes = [
            {
                path: "/workbench/index",
                name: "workbench",
                component: componentMap["../views/workbench/index.vue"],
            },
            {
                path: "/workbench/annoucement",
                name: "workbenchAnnoucement",
                component: componentMap["../views/workbench/annoucement.vue"],
            },
            {
                path: "/workbench/inbox-msg",
                name: "workbenchInboxMsg",
                component: componentMap["../views/workbench/inbox-msg.vue"],
            },
            {
                path: "/workbench/user",
                name: "workbenchUser",
                component: componentMap["../views/workbench/user.vue"],
            },
            {
                path: "/workbench/apps",
                name: "workbenchApps",
                component: componentMap["../views/workbench/apps.vue"],
            },
        ];
    } else {
        appRoutes = sysStore.appRoutes[appCode];
    }

    console.log(sysStore.appRoutes, appCode, appRoutes);

    if (!appRoutes) {
        return "/404";
    }

    if (router.hasRoute("app")) {
        router.removeRoute("app");
    }

    router.addRoute({
        path: "/" + appCode,
        name: "app",
        component: Index,
        children: appRoutes.map((item) => {
            if (item.cmp) {
                item.component = componentMap[item.cmp];
            }
            return item;
        }),
    });
    return to.fullPath;
});

export default router;
